package org.jcnc;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.json.JSONObject;

import java.io.*;
import java.net.InetSocketAddress;

/**
 * @author luke
 */
public class AccountService {

    public static void main(String[] args) throws Exception {
        int port = 8000;
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/register", new RegisterHandler());
        server.createContext("/login", new LoginHandler());
        server.createContext("/info", new InfoHandler());

        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port " + port);
    }

    static class RegisterHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) {
                try {
                    // 解析请求体
                    String requestBody = new String(exchange.getRequestBody().readAllBytes());
                    String[] params = requestBody.split("&");
                    String username = params[0].split("=")[1];
                    String password = params[1].split("=")[1];
                    String permission = params[2].split("=")[1];

                    // 存储到JSON文件
                    storeAccount(username, password, permission);

                    // 返回成功响应
                    String response = "Account created successfully";
                    exchange.sendResponseHeaders(200, response.getBytes().length);
                    OutputStream os = exchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 返回错误响应
                    String response = "Error occurred: " + e.getMessage();
                    exchange.sendResponseHeaders(500, response.getBytes().length);
                    OutputStream os = exchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                }
            } else {
                // 返回错误响应
                String response = "Only POST requests are allowed";
                exchange.sendResponseHeaders(405, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }

        private void storeAccount(String username, String password, String permission) throws IOException {
            JSONObject accountJSON = new JSONObject();
            accountJSON.put("username", username);
            accountJSON.put("password", password);
            accountJSON.put("permission", permission);

            try (FileWriter file = new FileWriter("accounts.json", true)) {
                file.write(accountJSON.toString());
                file.write("\n");
            }
        }
    }

    static class LoginHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) {
                try {
                    // 解析请求体
                    String requestBody = new String(exchange.getRequestBody().readAllBytes());
                    String[] params = requestBody.split("&");
                    String username = params[0].split("=")[1];
                    String password = params[1].split("=")[1];

                    // 从 JSON 文件中读取账户信息
                    JSONObject account = getAccount(username);

                    // 检查用户名和密码是否匹配
                    if (account != null && account.getString("password").equals(password)) {
                        // 返回成功响应
                        String response = "Login successful";
                        exchange.sendResponseHeaders(200, response.getBytes().length);
                        OutputStream os = exchange.getResponseBody();
                        os.write(response.getBytes());
                        os.close();
                    } else {
                        // 返回错误响应
                        String response = "Invalid username or password";
                        exchange.sendResponseHeaders(401, response.getBytes().length);
                        OutputStream os = exchange.getResponseBody();
                        os.write(response.getBytes());
                        os.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace(); // 打印异常堆栈信息
                    // 返回错误响应
                    String response = "Error occurred: " + e.getMessage();
                    exchange.sendResponseHeaders(500, response.getBytes().length);
                    OutputStream os = exchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                }

            } else {
                // 返回错误响应
                String response = "Only POST requests are allowed";
                exchange.sendResponseHeaders(405, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }

        private JSONObject getAccount(String username) throws IOException {
            // 从 JSON 文件中读取账户信息
            try (BufferedReader reader = new BufferedReader(new FileReader("accounts.json"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    JSONObject account = new JSONObject(line);
                    if (account.getString("username").equals(username)) {
                        return account;
                    }
                }
            }
            return null;
        }
    }

    static class InfoHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) {
                try {
                    // 解析请求体
                    String requestBody = new String(exchange.getRequestBody().readAllBytes());
                    String[] params = requestBody.split("&");
                    String username = params[0].split("=")[1];

                    // 从 JSON 文件中读取用户信息
                    JSONObject userInfo = getUserInfo(username);

                    // 返回用户信息
                    if (userInfo != null) {
                        String response = userInfo.toString();
                        exchange.sendResponseHeaders(200, response.getBytes().length);
                        OutputStream os = exchange.getResponseBody();
                        os.write(response.getBytes());
                        os.close();
                    } else {
                        // 用户信息不存在
                        String response = "User not found";
                        exchange.sendResponseHeaders(404, response.getBytes().length);
                        OutputStream os = exchange.getResponseBody();
                        os.write(response.getBytes());
                        os.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 返回错误响应
                    String response = "Error occurred: " + e.getMessage();
                    exchange.sendResponseHeaders(500, response.getBytes().length);
                    OutputStream os = exchange.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                }
            } else {
                // 返回错误响应
                String response = "Only POST requests are allowed";
                exchange.sendResponseHeaders(405, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }

        private JSONObject getUserInfo(String username) throws IOException {
            // 从 JSON 文件中读取用户信息
            try (BufferedReader reader = new BufferedReader(new FileReader("accounts.json"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    JSONObject userInfo = new JSONObject(line);
                    if (userInfo.getString("username").equals(username)) {
                        return userInfo;
                    }
                }
            }
            return null;
        }
    }


}

